import { login, logout, getInfo } from '@/api/login';
import { getToken, setToken, removeToken } from '@/utils/auth';
import { projectLisReceiveRemind, remindMum } from '@/api/third/project';
import { taskNotice } from '@/api/third/task';

import { MessageBox } from 'element-ui';
import router from '@/router';
const user = {
  state: {
    token: getToken(),
    userId: undefined,
    nickName: undefined,
    readNum: 0,
    name: '',
    avatar: '',
    roles: [],
    permissions: [],
    taskOverdueNum: 0,
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_ID: (state, userId) => {
      state.userId = userId;
    },
    SET_NICK_NAME: (state, nickName) => {
      state.nickName = nickName;
    },
    SET_READ_NUM: (state, readNum) => {
      state.readNum = readNum;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions;
    },
    SET_TASKNUM: (state, data) => {
      state.taskOverdueNum = data;
    },
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim();
      const password = userInfo.password;
      const code = userInfo.code;
      const uuid = userInfo.uuid;
      console.log("🚀 ~ file: user.js:60 ~ username, password, code, uuid:", username, password, code, uuid)
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid)
          .then(res => {
            setToken(res.token);
            commit('SET_TOKEN', res.token);
            resolve();
          })
          .catch(error => {
            reject(error);
          });
      });
    },

    // 获取用户信息
    GetInfo({ commit, state, dispatch }) {
      return new Promise((resolve, reject) => {
        getInfo(state.token)
          .then(res => {
            const user = res.user;
            const avatar = user.avatar == ''
              ? require('@/assets/image/profile.jpg')
              : process.env.VUE_APP_BASE_API + user.avatar;
            if (res.roles && res.roles.length > 0) {
              // 验证返回的roles是否是一个非空数组
              commit('SET_ROLES', res.roles);
              commit('SET_PERMISSIONS', res.permissions);
            } else {
              commit('SET_ROLES', ['ROLE_DEFAULT']);
            }
            commit('SET_NAME', user.userName);
            commit('SET_AVATAR', avatar);
            commit('SET_ID', user.userId);
            commit('SET_NICK_NAME', user.nickName);
            commit('SET_READ_NUM', res.readNum);

            // 因不知是否有用，暂时注释
            
            // setTimeout(() => {
            //   dispatch('ReceiveRemind');
            //   dispatch('TaskNum');
            // }, 2000);
            // setInterval(() => {
            //   dispatch('TaskNum');
            // }, 10000)
            resolve(res);
          })
          .catch(error => {
            reject(error);
          });
      });
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token)
          .then(() => {
            commit('SET_ID', undefined);
            commit('SET_TOKEN', '');
            commit('SET_ROLES', []);
            commit('SET_PERMISSIONS', []);
            removeToken();

            resolve();
          })
          .catch(error => {
            reject(error);
          });
      });
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '');
        removeToken();
        resolve();
      });
    },
    // 未读消息
    ReceiveRemind({ commit }) {
      return new Promise(resolve => {
        remindMum().then(res => {
          let { data } = res;
          openHtml(data);

          resolve(res);
        });
      });
    },
    /**任务数量 */
    TaskNum({ commit }) {
      return new Promise(resolve => {
        taskNotice().then(res => {
          let { data } = res;
          commit('SET_TASKNUM', data)
          resolve(res);
        });
      });
    },
  },
};
function openHtml(data) {
  let content = '';
  if (data.paperNum) {
    let nameList = '';
    for (let key of data.paperList) {
      nameList += `<div class='text-blue'>  ${key}</div>`;
    }
    nameList = `<div>${nameList}</div>`;
    content += `<div>
    您有<span class='text-red'>${data.paperNum}</span>未读提醒</div>
    ${nameList}
  `;
  }
  if (data.projectNum) {
    let nameList = '';
    for (let key of data.projectList) {
      nameList += `<div class='text-blue'>  ${key}</div>`;
    }
    nameList = `<div>${nameList}</div>`;
    content += `<div class='margin-top-xs'>
    您有<span class='text-red'>${data.projectNum}</span>个任务未完成
     
  </div>
  ${nameList}
  `;
  }
  if (content == '') {
    return;
  }
  MessageBox.confirm(`<div>${content}</div>`, '消息提示', {
    showClose: true,
    dangerouslyUseHTMLString: true,
    confirmButtonText: '前往处理',
    showCancelButton: false,
    customClass: 'paper-alert',
    closeOnPressEscape: false,
    closeOnClickModal: false,
  }).then(() => {
    router.push({
      path: '/prodData/paper',
    });
  });
}

export default user;
